const express = require('express')
const Topic = require('../models/topic')
const User = require('../models/user')


//路由容器
let router = express.Router()

//首页
router.get('/', async (req, res) => {
    try {
        let topicsList = await Topic.find()
        let total = topicsList.length
        let step = 5;
        let skip = req.query.skip - 1 || 0;
        let totalPage = Math.ceil(total/step);
        let totalPageToArr=[]
        for (let i=1;i <= totalPage;i++ ) {
            totalPageToArr.push(i)
        }
        let topics = await Topic.find().sort({'created_time':-1}).limit(step).skip(skip*step)
        
         let newtopics = topics.map( async (item)=>{
            
              let  user = await User.find({_id: item.user_id})
              let obj = {...item._doc,'user_avatar':user[0].avatar,'user_name':user[0].nickname}
              return obj          
        })
        Promise.all(newtopics).then((val)=>{
            res.render('index.html', {
                user: req.session.user,
                topics: val,
                totalPage: totalPageToArr,
                nowPage: skip+1
            })
        })
       
    } catch (err) {
        console.log(err)
    }

    
})

//访问 topic
router.get('/topic/:id', async (req, res) =>{

    let topic = await Topic.find({_id: req.params.id})

    res.render('topic/show.html', {
        user: req.session.user,
        topic:topic[0]
    })
})

//编辑 topic
router.get('/user/topic/edit/:id', async( req, res) => {
    let topic = await Topic.find({_id: req.params.id})

    res.render('topic/edit.html', {
        user: req.session.user,
        topic:topic[0]
    })
    
})
router.post('/user/topic/edit', async( req, res) => {
    if( !(req.body.title && req.body.topic ) ){
        return res.status(200).json({
            err_code:  1,
            message:'标题和内容都不能为空！',
        })
    }
    let topic_id = (req.body.id).replace(/\"|\'/g,'')
    console.log(topic_id);
    try {
        let result = await Topic.findOneAndUpdate({_id:topic_id},{
            title:req.body.title,
            topic:req.body.topic
        },function(err,doc){
            if(!err){
                return res.status(200).json({
                    err_code: 0,
                    message:'修改成功!将跳转到首页查看!',
                })
            }
        })  

    } catch (err) {
        return res.status(500).json({
            err_code:  500,
            message:'系统内部出现问题,请稍后再试!',
        })

    }
      
})
//删除
router.get('/user/topic/delete/:id', async (req, res) => {
    try{
        if(await Topic.findOneAndDelete({_id:req.params.id})){
            return res.status(200).json({
                err_code: 0,
                message:'删除成功,将跳转到首页!'
            })
        }else{
            return res.status(200).json({
                err_code: 1,
                message:'删除失败,请重试试!'
            })
        } 
         
   
    } catch (err) {
        console.log(err)
        return res.status(500).json({
            err_code: 2,
            message:'网站内部出现错误,请稍再试!'
        })
    }

})

//发表topic 需要登录后才能,所以路由选择由user 开头
//发表topic页面
router.get('/user/topics/new', async (req, res) => {
    res.render('topic/new.html',{
        user: req.session.user,
    })
})

//提交topic
router.post('/user/topics/new', async (req, res) => {
    if( !(req.body.title && req.body.topic ) ){
        return res.status(200).json({
            err_code:  1,
            message:'标题和内容都不能为空！',
        })
    }
    let topic = {
        title: req.body.title,
        topic: req.body.topic,
        user_id: req.session.user._id
    }
    try {
        let result = await new Topic(topic).save()
        return res.status(200).json({
            err_code: 0,
            message:'发表成功!将跳转到首页查看!',
        })
    } catch (err) {
        return res.status(500).json({
            err_code:  500,
            message:'系统内部出现问题,请稍后再试!',
        })

    }
    
})


module.exports = router